import pymysql
import os
import shutil
import cv2
import tkinter


db = pymysql.connect(host='localhost', user='root', passwd='12345', database='faceadd')
cursor = db.cursor()
male = []
female = []
hairNameMale = []
hairNameFemale = []
gender = ''
index = 0
def setGender(g):
    global gender
    gender = g

#删除文件夹后创建同名空文件夹
def deletGraph(file):#file是文件夹路径
    if os.path.exists(file):
        shutil.rmtree(file)

    a = os.path.exists(file)#文件是否存在
    if(a==False):
        os.mkdir(file)
def getHair(index=-1,name=None):#从数据库拿出发型放到本地文件夹，hair是提前放好的所有信息都有
    sql = 'select * from hair'
    cursor.execute(sql)
    a = cursor.fetchall()
    index = 0
    while index < len(a):
        c = a[index][1]
        if a[index][3] == 'm':
            with open(r'D:\Face\Man\{}.png'.format(a[index][2]), 'wb') as f:
                f.write(c)
            male.append(cv2.imread(r'D:\Face\Man\{}.png'.format(a[index][2])))
            hairNameMale.append(a[index][2])
        elif a[index][3] == 'f':
            with open(r'D:\Face\Woman\{}.png'.format(a[index][2]), 'wb') as f:
                f.write(c)
            female.append(cv2.imread(r'D:\Face\Woman\{}.png'.format(a[index][2])))
            hairNameFemale.append(a[index][2])
        index = index + 1
    deletGraph(r'D:\Face\Man')
    deletGraph(r'D:\Face\Woman')
def showHair(gender):
    global index
    if gender == 'm':
        cv2.imshow('jpg',male[index])
    elif gender == 'f':
        cv2.imshow('jpg', female[index])
    cv2.waitKey(0)
def nextPage():
    global index
    index += 1
    if index>19:#一共20张照片
        index = 19
    showHair(gender)
def lastPage():
    global index
    index -= 1
    if index<0:
        index = 0
    showHair(gender)
# def swap():
#     if gender == 'm':
#         hairChange.main(hairNameMale[index]+'.png','m')
#     elif gender == 'f':
#         hairChange.main(hairNameFemale[index]+'.png','f')

def main(g):
    getHair()  # 头发存在列表里
    setGender(g)
    win = tkinter.Tk()
    win.title('选择')
    win.geometry('400x100+400+100')

    b1 = tkinter.Button(win, text='上一页', command=lastPage, height=2, width=10)
    b1.place(x=50, y=50)
    b2 = tkinter.Button(win, text='下一页', command=nextPage, height=2, width=10)
    b2.place(x=150, y=50)
    b3 = tkinter.Button(win, text='确定', height=2, width=10)
    b3.place(x=250, y=50)

    showHair(gender)

    win.mainloop()
if __name__ == '__main__':
     main('m')